<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\models\{Lists, Peizhi, Ecsource, Laiyuan, Liaotian};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\facade\Log;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function test()
    {
        $data = (new Liaotian())->group('date')->field('date,count(users) as liaotian')->select();
        foreach ($data as $row) {
            $row['fang'] = (new Liaotian())->where(['users' => '方玉洁', 'date' => $row['date']])->count();
            $row['zou'] = (new Liaotian())->where(['users' => '邹鹏飞', 'date' => $row['date']])->count();
        }
        return $data;
    }

    public function list_ks()
    {
        $data = input();
        if (empty($data['type'])) {
            $this->result([], 1, '获取失败,未设置品牌参数');
        }
        Log::write($data, 'ks_data');
        $data['location'] = '';
        if (!empty($data['intention_province_name'])) {
            $data['location'] = $data['intention_province_name'];
        }
        if (!empty($data['intention_city_name'])) {
            $data['location'] = $data['location'] . ' ' . $data['intention_city_name'];
        }
        $data['create_time_second'] = $data['create_time_second'] ?? 0;
        $data['create_time_second'] = (int)$data['create_time_second'] ?? 0;
        $saves = [
            'crmtype' => 2,
            'laiyuan' => $data['laiyuan'] ?? '未知',
            'clue_id' => $data['id'] ?? '',
            'type' => $data['type'] ?? 0,
            'pinpai' =>  $data['pinpai'] ?? ((new Peizhi())->where(['type' => $data['type']])->value('pinpai') ?? ""),
            'name' =>  $data['consumer_name'] ?? "",
            'phone' =>  $data['phone'] ?? "",
            'address' => $data['location'] ?? "",
            'othertel' =>  $data['we_chat'] ?? "",
            // 'pingtai' =>  $data['app_name'] ?? "",
            //'source' =>  $data['biz_source'] ?? 1,
            'remark' =>   $data['remark'] ?? "",
            'created' =>  date('Y-m-d H:i:s', ($data['create_time_second'] ?? 0)),
            'allocation' => 1,
            'repeats' => 1,
            'datas' => json_encode(($data ?? []), true),
            'adv_id' =>  $data['unit_id'] ?? "",
            'cid' =>  $data['creative_id'] ??  "",
            'ad_id' =>  $data['campaign_id'] ??  "",
            'promotion_id' =>  $data['attr_clue_account_id'] ??  "",
            'videoid' =>  $data['photo_id'] ?? "",
            'clue_source' => $data['clue_source'] ?? 0, //原始来源
            'clue_source_text' => '', //文本来源
        ];
        $have =  (new Lists())->where(['crmtype' => 2, 'type' => $saves['type'], 'phone' => $saves['phone'], 'isdel' => 1, 'created' => $saves['created']])->find();
        if (!empty($saves['othertel']) && empty($have)) {
            $have =  (new Lists())->where(['crmtype' => 2, 'type' => $saves['type'], 'othertel' => $saves['othertel'], 'isdel' => 1, 'created' => $saves['created']])->find();
        }
        if (empty($have) && !empty($saves['xxid'])) {
            $have =  (new Lists())->where(['crmtype' => 2, 'xxid' => $saves['xxid'], 'type' => $saves['type'], 'isdel' => 1])->find();
        }
        if (!empty($have)) {
            $this->result([], 0, '已添加成功');
        }
        if (empty($saves['phone']) && empty($saves['othertel'])) {
            $this->result([], 1, '手机号或微信获取失败');
        }
        //检测同一品牌是否重复
        $reother = [];
        if (!empty($saves['phone'])) {
            $reother =  (new Lists())->where(['type' => $saves['type'], 'phone' => $saves['phone'], 'isdel' => 1])->find();
        }
        if (!empty($saves['othertel']) && empty($reother)) {
            $reother =  (new Lists())->where(['type' => $saves['type'], 'othertel' => $saves['othertel'], 'isdel' => 1])->find();
        }
        if (!empty($reother)) {
            $saves['repeats'] = 2;
        }
        Db::startTrans();
        try {
            (new Lists())->allowfield(true)->save($saves);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage(), 'getdatalist');
            $this->result([], 1, $e->getMessage());
        }
        try {
            $this->testAddCustomer();
        } catch (\Exception $e) {
        }
        $this->result([], 0, '添加成功');
    }

    public function list()
    {
        $data = input();
        if (empty($data['type'])) {
            $this->result([], 1, '获取失败,未设置品牌参数');
        }
        Log::write($data, 'getdatalist');
        if (!empty($data['location'])) {
            $data['location'] = str_replace("+", " ", $data['location']);
        }
        $video = 0;
        if (!empty($data['mid_info'])) {
            $mid_info = json_decode($data['mid_info'], true);
            $video = $mid_info['videoId'] ?? 0;
        }

        $saves = [
            'crmtype' => 1,
            'laiyuan' => $data['laiyuan'] ?? '未知',
            'xxid' => $data['id'] ?? '',
            'type' => $data['type'] ?? 0,
            'pinpai' =>  $data['pinpai'] ?? ((new Peizhi())->where(['type' => $data['type']])->value('pinpai') ?? ""),
            'name' =>  $data['name'] ?? "",
            'phone' =>  $data['telphone'] ?? "",
            'address' => $data['location'] ?? "",
            'othertel' =>  $data['weixin'] ?? "",
            'pingtai' =>  $data['app_name'] ?? "",
            'source' =>  $data['clue_type'] ?? 1,
            'remark' =>   $data['remark'] ?? "",
            'created' =>  date('Y-m-d H:i:s', ($data['create_time'] ?? 0)),
            'allocation' => 1,
            'repeats' => 1,
            'datas' => json_encode(($data ?? []), true),
            'adv_id' =>  $data['adv_id'] ?? "",
            'cid' =>  $data['cid'] ??  "",
            'ad_id' =>  $data['ad_id'] ??  "",
            'promotion_id' =>  $data['promotion_id'] ??  "",
            'videoid' =>  $video ?? "",
            'clue_source' => $data['clue_source'] ?? 0, //原始来源
            'clue_source_text' => '', //文本来源
        ];
        $have =  (new Lists())->where(['crmtype' => 1, 'type' => $saves['type'], 'phone' => $saves['phone'], 'isdel' => 1, 'created' => $saves['created']])->find();
        if (!empty($saves['othertel']) && empty($have)) {
            $have =  (new Lists())->where(['crmtype' => 1, 'type' => $saves['type'], 'othertel' => $saves['othertel'], 'isdel' => 1, 'created' => $saves['created']])->find();
        }
        if (empty($have) && !empty($saves['xxid'])) {
            $have =  (new Lists())->where(['crmtype' => 1, 'xxid' => $saves['xxid'], 'type' => $saves['type'], 'isdel' => 1])->find();
        }
        if (!empty($have)) {
            $this->result([], 0, '已添加成功');
        }
        //飞鱼CRM
        $fylaiyuan = array(
            0 => '巨量广告',
            1 => '巨量广告',
            2 => "外部导入",
            5 => "抖音企业号",
            7 => "巨量线索",
            8 => "云店",
            9 => "星图",
            10 => "获客宝",
            11 => "住小帮"
        );
        $saves['clue_source_text'] = $fylaiyuan[$saves['clue_source']] ?? '';
        if (empty($saves['phone']) && empty($saves['othertel'])) {
            $this->result([], 1, '获取失败');
        }
        //检测同一品牌是否重复
        $reother = [];
        if (!empty($saves['phone'])) {
            $reother =  (new Lists())->where(['type' => $saves['type'], 'phone' => $saves['phone'], 'isdel' => 1])->find();
        }
        if (!empty($saves['othertel']) && empty($reother)) {
            $reother =  (new Lists())->where(['type' => $saves['type'], 'othertel' => $saves['othertel'], 'isdel' => 1])->find();
        }
        if (!empty($reother)) {
            $saves['repeats'] = 2;
        }
        Db::startTrans();
        try {
            (new Lists())->allowfield(true)->save($saves);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage(), 'getdatalist');
            $this->result([], 1, $e->getMessage());
        }
        try {
            $this->testAddCustomer();
        } catch (\Exception $e) {
        }
        $this->result([], 0, '添加成功');
    }

    function testAddCustomer()
    {
        // $peizhi = (new Peizhi())->where(['type' => 1])->find();
        // $url = "https://open.workec.com/v2/customer/getChannelSource";
        // list($returnCode, $returnContent) = doGet($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $url, []);
        // $rjson = json_decode($returnContent, true);
        // $save = [];
        // foreach ($rjson['data'] as $js) {
        //     $save[] = [
        //         'type' => 1,
        //         'ecid' => $js['id'],
        //         'ecname' => $js['name'],
        //         'ecgroupId' => $js['groupId'],
        //         'ecgroupName' => $js['groupName'],
        //         'created' => date('Y-m-d H:i:s')
        //     ];
        // }
        // Db::startTrans();
        // try {
        //     (new Ecsource())->where(['type' => 1])->delete();
        //     (new Ecsource())->allowfield(true)->saveAll($save);
        //     Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     Log::write($e->getMessage(), 'getdata');
        //     Log::write($rjson, 'getdata');
        // }
        // die;
        //获取待分配数据
        $list = (new Lists())->where(['allocation' => 1, 'repeats' => 1, 'isdel' => 1])->select();
        foreach ($list as $row) {
            Log::write($row['id'] . '-----------开始', 'getdata');
            //查找配置参数
            $peizhi = (new Peizhi())->where(['type' => $row['type']])->find();
            if (!empty($peizhi)) {
                //EC平台手机号查重
                if (empty($row['phone'])) {
                    $row['phone'] = '13' . date('ymd') . mt_rand(100, 999);
                    $row['name'] = $row['name'] . '(手机是虚拟号请联系微信)';
                }
                if (!empty($row['phone'])) {
                    //进行查询
                    $ccdata = [
                        "mobile" => $row['phone'], //来源ID
                        "maxNumsPreMobile" => 0
                    ];
                    $ccjsonData = json_encode($ccdata);
                    // 2. 请求服务器处理
                    $ccurl = "https://open.workec.com/v2/customer/queryExist";
                    list($ccreturnCode, $ccreturnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $ccurl, $ccjsonData);
                    $ccrjson = json_decode($ccreturnContent, true) ?? [];
                    if (!empty($ccrjson['code']) && $ccrjson['code'] == 200 && !empty($ccrjson['data']) && count($ccrjson['data']) > 0 && !empty($ccrjson['data'][0]['num'])) {
                        Db::startTrans();
                        try {
                            (new Lists())->where(['id' => $row['id']])->update(['repeats' => 2]);
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                            Log::write($e->getMessage(), 'getdata');
                            Log::write($ccjsonData, 'getdata');
                        }
                        continue;
                    } elseif (!empty($ccrjson['code']) && $ccrjson['code'] != 200) {
                        continue;
                    }
                }
                $row['phone'] = trim($row['phone']);
                //获取来源ID
                $laiyuanfind = (new Laiyuan())->where(['type' => $row['type'], 'ly' => $row['adv_id']])->find();
                if (empty($laiyuanfind) && !empty($row['adv_id'])) {
                    (new Laiyuan())->allowfield(true)->save([
                        'type' => $row['type'],
                        'ly' => $row['adv_id'],
                        'ecRcm' => $peizhi['wzly'] ?? 0,
                    ]);
                    Log::write('插入来源广告', 'getdata');
                }
                $laiyuan = $laiyuanfind['ecRcm'] ?? 0;
                if (empty($laiyuan)) {
                    $laiyuan = $peizhi['wzly'] ?? 0;
                    Log::write('使用默认来源', 'getdata');
                }
                if (empty($laiyuan)) {
                    Log::write('未设置默认来源跳过', 'getdata');
                    continue;
                }
                //进行推送
                $data = [
                    "name" => $row['name'] ?? '',
                    "phone" => $row['phone'] ?? '',
                    "source" => $laiyuan, //来源ID
                    "wx" => $row['othertel'] ?? '',
                    "remark" => $row['remark'] ?? '',
                ];
                $jsonData = json_encode($data);
                // 2. 请求服务器处理
                $url = "https://open.workec.com/v2/clue/import";
                list($returnCode, $returnContent) = doPost($peizhi['cid'], $peizhi['appId'], $peizhi['appSecret'], $url, $jsonData);
                $rjson = json_decode($returnContent, true);
                Log::write($rjson, 'getdata2');
                if (!empty($rjson['code']) && $rjson['code'] == 200) {
                    Db::startTrans();
                    try {
                        (new Lists())->where(['id' => $row['id']])->update(['allocation' => 2, 'fplaiyuan' => $laiyuan, 'phone' => $data['phone']]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        Log::write($e->getMessage(), 'getdata');
                        Log::write($rjson, 'getdata');
                    }
                }
            }
            Log::write($row['id'] . '-----------结束', 'getdata');
        }
    }
}
